<template>
  <div class="global-search">
    <el-autocomplete
      v-model="searchQuery"
      :fetch-suggestions="querySearch"
      placeholder="输入学号或姓名搜索学生"
      @select="handleSelect"
      class="search-input"
    >
      <template slot-scope="{ item }">
        <div class="search-suggestion">
          <div class="suggestion-name">{{ item.studentName }}</div>
          <div class="suggestion-id">学号: {{ item.studentId }}</div>
        </div>
      </template>
      <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
    </el-autocomplete>

    <!-- 搜索结果展示 -->
    <el-dialog title="搜索结果" :visible.sync="dialogVisible" width="80%">
      <el-table :data="searchResults" style="width: 100%" v-loading="loading">
        <el-table-column prop="studentId" label="学号"></el-table-column>
        <el-table-column prop="studentName" label="姓名"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="totalScore" label="总分"></el-table-column>
        <el-table-column label="出勤率" width="180">
          <template slot-scope="scope">
            <el-progress 
              :percentage="scope.row.attendanceRate" 
              :color="getAttendanceColor(scope.row.attendanceRate)">
            </el-progress>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-button @click="viewStudentDetail(scope.row)" type="primary" size="small">查看详情</el-button>
            <el-button @click="showPrediction(scope.row)" type="warning" size="small">缺勤预测</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 缺勤预测结果 -->
    <el-dialog 
      title="缺勤预测" 
      :visible.sync="predictionVisible" 
      width="50%" 
      append-to-body
    >
      <div v-if="predictionLoading" style="text-align: center; padding: 20px;">
        <el-spinner></el-spinner>
        <p>预测计算中...</p>
      </div>
      <div v-else>
        <div class="prediction-header">
          <el-avatar :size="64" :src="currentStudent.avatar || ''">
            {{ currentStudent.studentName ? currentStudent.studentName.substring(0, 1) : 'S' }}
          </el-avatar>
          <div class="student-info">
            <h3>{{ currentStudent.studentName }}</h3>
            <p>学号: {{ currentStudent.studentId }}</p>
          </div>
        </div>
        
        <el-divider content-position="center">最可能缺勤的课程</el-divider>
        
        <div v-if="predictions.length > 0">
          <el-card 
            v-for="(prediction, index) in predictions" 
            :key="index"
            class="prediction-card"
            :class="{'high-risk': prediction.probability > 75}"
          >
            <div class="prediction-content">
              <div class="course-info">
                <h4>{{ prediction.courseName }}</h4>
                <p>课程编号: {{ prediction.courseId }}</p>
                <p>历史出勤率: {{ prediction.historicalAttendance }}%</p>
              </div>
              <div class="probability">
                <el-progress type="circle" 
                  :percentage="prediction.probability" 
                  :color="getPredictionColor(prediction.probability)">
                </el-progress>
                <p>缺勤概率</p>
              </div>
            </div>
            <div class="prediction-factors">
              <el-tag 
                v-for="(factor, i) in prediction.factors" 
                :key="i" 
                size="small" 
                :type="getFactorType(i)"
                style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ factor }}
              </el-tag>
            </div>
          </el-card>
        </div>
        <div v-else class="no-predictions">
          <el-empty description="没有可用的缺勤预测数据"></el-empty>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'StudentSearch',
  data() {
    return {
      searchQuery: '',
      searchResults: [],
      dialogVisible: false,
      loading: false,
      predictions: [],
      predictionVisible: false,
      predictionLoading: false,
      currentStudent: {},
      searchTimeout: null
    };
  },
  methods: {
    async querySearch(queryString, callback) {
      if (queryString.length < 2) {
        callback([]);
        return;
      }
      
      // 使用防抖，避免频繁请求
      clearTimeout(this.searchTimeout);
      this.searchTimeout = setTimeout(async () => {
        try {
          const response = await this.$request.get('/api/dashboard/search', {
            params: { query: queryString }
          });
          
          if (response && Array.isArray(response.data)) {
            callback(response.data.slice(0, 10)); // 只显示前10个结果作为建议
          } else {
            callback([]);
          }
        } catch (error) {
          console.error('搜索请求失败:', error);
          callback([]);
        }
      }, 300);
    },
    
    handleSelect(item) {
      this.viewStudentDetail(item);
    },
    
    async search() {
      if (!this.searchQuery || this.searchQuery.length < 2) {
        this.$message.warning('请输入至少2个字符进行搜索');
        return;
      }
      
      this.loading = true;
      this.dialogVisible = true;
      
      try {
        const response = await this.$request.get('/api/dashboard/search', {
          params: { query: this.searchQuery }
        });
        
        if (response && Array.isArray(response.data)) {
          this.searchResults = response.data;
        } else {
          this.searchResults = [];
          this.$message.info('未找到匹配的学生');
        }
      } catch (error) {
        console.error('搜索请求失败:', error);
        this.$message.error('搜索失败，请稍后重试');
        this.searchResults = [];
      } finally {
        this.loading = false;
      }
    },
    
    viewStudentDetail(student) {
      this.$router.push(`/main/student/${student.studentId}`);
      this.dialogVisible = false;
    },
    
    async showPrediction(student) {
      this.currentStudent = student;
      this.predictionVisible = true;
      this.predictionLoading = true;
      this.predictions = [];
      
      try {
        const response = await this.$request.get(`/api/dashboard/absence-prediction/${student.studentId}`);
        
        if (response && Array.isArray(response.data)) {
          this.predictions = response.data.map(item => ({
            ...item,
            // 添加默认值以防数据不完整
            probability: item.probability || item.absentProbability || 0,
            historicalAttendance: item.historicalAttendance || 0,
            factors: item.factors || ['历史出勤记录', '课程难度', '时间因素']
          }));
        } else {
          this.$message.info('没有可用的预测数据');
        }
      } catch (error) {
        console.error('获取预测失败:', error);
        this.$message.error('预测数据加载失败');
      } finally {
        this.predictionLoading = false;
      }
    },
    
    getAttendanceColor(rate) {
      if (rate < 60) return '#F56C6C';
      if (rate < 80) return '#E6A23C';
      return '#67C23A';
    },
    
    getPredictionColor(probability) {
      if (probability > 75) return '#F56C6C';
      if (probability > 50) return '#E6A23C';
      return '#67C23A';
    },
    
    getFactorType(index) {
      const types = ['', 'success', 'warning', 'info', 'danger'];
      return types[index % types.length];
    }
  }
};
</script>

<style scoped>
.global-search {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
}

.search-input {
  width: 100%;
}

.search-suggestion {
  padding: 5px 0;
}

.suggestion-name {
  font-weight: bold;
}

.suggestion-id {
  font-size: 12px;
  color: #909399;
}

.prediction-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.student-info {
  margin-left: 15px;
}

.student-info h3 {
  margin: 0 0 5px 0;
}

.student-info p {
  margin: 0;
  color: #909399;
}

.prediction-card {
  margin-bottom: 15px;
}

.prediction-card.high-risk {
  border: 1px solid #F56C6C;
}

.prediction-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-info h4 {
  margin: 0 0 5px 0;
}

.course-info p {
  margin: 3px 0;
  color: #606266;
  font-size: 13px;
}

.probability {
  text-align: center;
}

.probability p {
  margin: 5px 0 0 0;
  font-size: 12px;
}

.prediction-factors {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #EBEEF5;
}

.no-predictions {
  padding: 20px;
  text-align: center;
}
</style>